from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from goods.models import GoodsVisitCount, SPUSpecification, SPU, SKUImage, SKU
from users.models import User


# 日分类商品访问量的商品访问数据模型序列化器
class GoodsSerializer(ModelSerializer):
    # 指定返回分类名称 read_only ： 表明该字段仅用于序列化输出，默认False
    category = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = GoodsVisitCount
        fields = ('count', 'category')  # 基于模型类生成所选择序列化的字段


# 用户统计用户模型序列化器
class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')
        # extra_kwargs = {
        #     'username':{
        #         'max_length': 20,
        #         'min_length': 5
        #     },
        #     'password':{
        #         'max_length': 20,
        #         'min_length': 8,
        #         'write_only': True
        #     }
        # }


class UserAddSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            }
        }

    # 重写create 方法，增加密码加密功能
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user


# 商品规格序列化器
class SPUSpecificationSerializer(ModelSerializer):
    '''
    规格序列化器
    '''
    # 关联嵌套返回spu表的商品名
    spu = serializers.StringRelatedField(read_only=True)
    # 返回关联spu的id值
    spu_id = serializers.IntegerField()

    class Meta:
        model = SPUSpecification  # 商品规格表关联了spu表的外键spu
        fields = '__all__'


class SPUSerializer(ModelSerializer):
    """
    添加框里的SPU信息,就是查找不包括配置的商品
    """
    class Meta:
        model = SPU
        fields = ['id', 'name']


class ImageSerializer(ModelSerializer):
    """
    图片的序列化器
    """
    # 返回图片关联的sku的id值
    sku = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = SKUImage
        fields = ['sku', 'image', 'id']


class SKUSimple(ModelSerializer):
    """
    增加窗口弹出的下拉选项数据展示序列化器
    """
    class Meta:
        model = SKU
        fields = ['id', 'name']